<template>
  <div class="callback-page">
    <div class="spinner-grows">
      <div class="spinner-grow"></div>
      <div class="spinner-grow"
           style="animation-delay:0.1s"></div>
      <div class="spinner-grow"
           style="animation-delay:0.2s"></div>
    </div>
    <div class="message-text">正在验证身份信息...</div>
  </div>
</template>

<script lang="ts">
  import { CURRENT_BASE_URL, urlCombine } from "@/framework/utilities";
  import { Component, Vue } from "@some21/vue-class-decorator";
  import { UserManager } from "oidc-client";

  const mgr = new UserManager({ response_mode: "query" });

  @Component({
    name: "CallbackPage",
  })
  export default class extends Vue {
    async mounted() {
      try {
        const user = await mgr.signinRedirectCallback();
        window.location.replace(user.state?.url || "/");
      } catch (err: any) {
        console.error(err);
        const faildPageUrl = urlCombine(CURRENT_BASE_URL, "Failed.html");
        if (err.message) {
          if (err.message.startsWith("iat is in the future:") || err.message.startsWith("exp is in the past:")) {
            faildPageUrl.searchParams.append("errCode", "CLIENT_TIME_FAILED");
          } else if (err.message.startsWith("No matching state found in storage")) {
            // 没有获取到用户信息的存储时，应当重试一次
            window.location.replace(CURRENT_BASE_URL);
            return;
          } else {
            faildPageUrl.searchParams.append("errCode", "UNKNOW_FAILED");
            faildPageUrl.searchParams.append("errMsg", err.message);
          }
        } else {
          faildPageUrl.searchParams.append("errCode", "UNKNOW_FAILED");
          faildPageUrl.searchParams.append("errMsg", err.message);
        }

        window.location.replace(faildPageUrl);
      }
    }
  }
</script>

<style lang="scss" scoped>
  .callback-page {
    display: flex;
    height: 100%;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }
  @keyframes spinner-grow {
    0% {
      transform: scale(0);
    }
    50% {
      opacity: 1;
      transform: none;
    }
  }
  .spinner-grows {
    margin-bottom: 10px;
    display: flex;
  }
  .spinner-grow {
    width: 32px;
    height: 32px;
    display: block;
    background-color: #0d6efd;
    border-radius: 50%;
    font-size: 0;
    opacity: 0;
    line-height: 1;
    padding: 0;
    margin: 0;
    animation: 0.75s linear infinite spinner-grow;
  }

  .message-text {
    color: #6c757d;
  }
</style>
